//
//  WmcEditWatermarkVM.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/10.
//

import RxRelay
import UIKit
import YPBedrock

class WmcEditWatermarkVM: WmcBaseVM {
    // MARK: 参数

    /// 水印模型
    var watermarkModel: WmcWatermarkDetailModel?
    
    /// 渲染模式，默认动态，列表实时更新
    /// 静态则根据模型内容进行渲染
    var watermarkStyleMode: WmcBaseWatermarkTemplateView.StyleMode = .dynamicDraw
    
    // MARK: 输出

    /// 编辑列表
    var editListRelay: BehaviorRelay<[WmcWatermarkOptionModel]> = .init(value: [])
    
    /// 编辑的水印模型
    var editWatermarkModelRelay: BehaviorRelay<WmcWatermarkDetailModel?> = .init(value: nil)

    // MARK: 回调

    /// 编辑完成的回调
    var editCompleteBlock: YPBlock.OneParam<WmcWatermarkDetailModel>?

    // MARK: 输入

    /// 获取水印标题
    var watermarkTitle: String {
        var title = watermarkModel?.name ?? "返回"
        title = title.yp.appendSuffix(string: "水印")
        return title
    }

    /// 加载数据
    func loadData() {
        guard let watermarkModel = watermarkModel else { return }
        // 加载编辑数据
        editListRelay.accept(watermarkModel.fields)
        editWatermarkModelRelay.accept(watermarkModel)
    }

    /// 修改元素属性
    func changeField(_ idx: Int, option: WmcWatermarkOptionModel) {
        var fields = editListRelay.value
        if !fields.yp.isCrossing(idx) {
            fields[idx] = option
        }
        editListRelay.accept(fields)
        // 修改模型
        watermarkModel?.fields = fields
        loadData()
    }

    /// 修改大小
    func changeSize(_ size: Int) {
        watermarkModel?.size = size
        loadData()
    }

    /// 修改透明
    func changeAlpha(_ alpha: Int) {
        watermarkModel?.alpha = alpha
        editWatermarkModelRelay.accept(watermarkModel)
        yp.delayLast(0.3) { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.loadData()
        }
    }

    /// 更新水印模型
    func updateWatermarkModel(_ wm: WmcWatermarkDetailModel) {
        watermarkModel = wm
        loadData()
    }

    /// 编辑完成回调
    func editComplete() {
        guard let watermarkModel = watermarkModel else { return }
        // 存储用户编辑数据
        WmcUserEditWatermarksDBManager.insertWatermarkModel(watermarkModel) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.editCompleteBlock?(watermarkModel)
        }
    }
}
